<?php

declare(strict_types=1);

namespace app\eslib;

use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use think\facade\Config;

/**
 * 邮件 助手类
 * @version 1.0.0
 * 依赖: composer require symfony/mailer (php8.0+)
 * 文档: https://symfony.com/doc/current/mailer.html
 */
class EsMailOfMailer
{
    protected $user = '';
    protected $password = '';
    protected $host = '';
    protected $port = 25;
    protected $fromEmail = [];

    public function initByConfig()
    {
        $smtpInfo = Config::get('site.email.smtp');
        if (!isset($smtpInfo['password'])) {
            return;
        }
        $this->user = $smtpInfo['username'];
        $this->password = $smtpInfo['password'];
        $this->host = $smtpInfo['host'];
        $this->port = $smtpInfo['port'];
    }
    public function setSmtp($user, $password, $host, $port = 25)
    {
        $this->user = $user;
        $this->password = $password;
        $this->host = $host;
        $this->port = $port;
    }
    public function send($subject, $body, $toEmail, $fromEmail = '')
    {
        if ($fromEmail) {
            $this->fromEmail = $fromEmail;
        } else {
            $fromEmail = $this->fromEmail;
        }
        if (!$fromEmail || !$toEmail || !$subject) {
            return stdmessage(0, '参数无效');
        }
        // Create the Transport
        $transport = (new Swift_SmtpTransport($this->host, $this->port))
            ->setUsername($this->user)
            ->setPassword($this->password);

        // Create the Mailer using your created Transport
        $mailer = new Swift_Mailer($transport);

        // Create a message
        $message = (new Swift_Message($subject))
            ->setFrom($fromEmail)
            ->setTo($toEmail)
            ->setBody($body);

        // Send the message
        $result = $mailer->send($message);
        return stdmessage($result, $result ? '' : '发送失败');
    }
}
